package com.mm.cloth.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.mm.cloth.R;
import com.mm.cloth.view.MaskDrawingView;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class MattingActivity extends AppCompatActivity {
    private static final String TAG = "MattingActivity";
    private static final int REQUEST_PERMISSION = 100;
    private static final int REQUEST_ORIGINAL_IMAGE = 101;
    private static final int REQUEST_MASK_IMAGE = 102;
    private static final int REQUEST_DRAW_MASK = 103;
    
    private ImageView ivOriginalImage;
    private FrameLayout flImageContainer;
    private LinearLayout llUploadHint;
    private MaskDrawingView maskDrawingView;
    private Button btnUploadOriginal;
    private Button btnUploadMask;
    private Button btnDrawMask;
    private Button btnEditMask;
    private Button btnClearMask;
    private Button btnSubmit;
    private ProgressBar progressBar;
    
    private Bitmap originalBitmap;
    private Bitmap maskBitmap;
    private String originalImageUriString;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_matting);
        
        initViews();
        setupClickListeners();
        checkPermissions();
    }
    
    private void initViews() {
        ivOriginalImage = findViewById(R.id.ivOriginalImage);
        flImageContainer = findViewById(R.id.flImageContainer);
        llUploadHint = findViewById(R.id.llUploadHint);
        maskDrawingView = findViewById(R.id.maskDrawingView);
        btnUploadOriginal = findViewById(R.id.btnUploadOriginal);
        btnUploadMask = findViewById(R.id.btnUploadMask);
        btnDrawMask = findViewById(R.id.btnDrawMask);
        btnEditMask = findViewById(R.id.btnEditMask);
        btnClearMask = findViewById(R.id.btnClearMask);
        btnSubmit = findViewById(R.id.btnSubmit);
        progressBar = findViewById(R.id.progressBar);
        
        // 设置标题栏
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("AI抠图");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }
    
    private void setupClickListeners() {
        btnUploadOriginal.setOnClickListener(v -> selectOriginalImage());
        btnUploadMask.setOnClickListener(v -> selectMaskImage());
        btnDrawMask.setOnClickListener(v -> startDrawMask());
        btnEditMask.setOnClickListener(v -> editExistingMask());
        btnClearMask.setOnClickListener(v -> clearMask());
        btnSubmit.setOnClickListener(v -> submitMatting());
        
        // 返回按钮
        findViewById(R.id.btnBack).setOnClickListener(v -> finish());
    }
    
    private void checkPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    REQUEST_PERMISSION);
        }
    }
    
    private void selectOriginalImage() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        startActivityForResult(intent, REQUEST_ORIGINAL_IMAGE);
    }
    
    private void selectMaskImage() {
        if (originalBitmap == null) {
            Toast.makeText(this, "请先上传原图", Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        startActivityForResult(intent, REQUEST_MASK_IMAGE);
    }

    private void startDrawMask() {
        if (originalBitmap == null) {
            Toast.makeText(this, "请先上传原图", Toast.LENGTH_SHORT).show();
            return;
        }

        // 启动遮罩绘制页面（新建遮罩）
        Intent intent = new Intent(this, MaskDrawingActivity.class);
        intent.putExtra(MaskDrawingActivity.EXTRA_ORIGINAL_IMAGE_URI, getOriginalImageUri());
        startActivityForResult(intent, REQUEST_DRAW_MASK);
    }

    private void editExistingMask() {
        if (originalBitmap == null) {
            Toast.makeText(this, "请先上传原图", Toast.LENGTH_SHORT).show();
            return;
        }

        if (maskBitmap == null && !maskDrawingView.hasMask()) {
            Toast.makeText(this, "没有可编辑的遮罩，请先绘制或上传遮罩", Toast.LENGTH_SHORT).show();
            return;
        }

        // 启动遮罩绘制页面（编辑现有遮罩）
        Intent intent = new Intent(this, MaskDrawingActivity.class);
        intent.putExtra(MaskDrawingActivity.EXTRA_ORIGINAL_IMAGE_URI, getOriginalImageUri());

        // 如果有现有遮罩，传递给编辑页面
        if (maskBitmap != null) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            maskBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            intent.putExtra(MaskDrawingActivity.EXTRA_EXISTING_MASK, byteArray);
        }

        startActivityForResult(intent, REQUEST_DRAW_MASK);
    }

    private String getOriginalImageUri() {
        return originalImageUriString;
    }
    
    private void submitMatting() {
        if (originalBitmap == null) {
            Toast.makeText(this, "请先上传原图", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (maskBitmap == null && !maskDrawingView.hasMask()) {
            Toast.makeText(this, "请上传遮罩图或在原图上绘制遮罩", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 显示加载状态
        showLoading(true);
        
        // 模拟API调用
        mockMattingAPI();
    }
    
    private void mockMattingAPI() {
        // 模拟网络请求延迟
        new Thread(() -> {
            try {
                Thread.sleep(3000); // 模拟3秒处理时间
                
                runOnUiThread(() -> {
                    showLoading(false);
                    Toast.makeText(this, "抠图处理完成！", Toast.LENGTH_LONG).show();
                    
                    // TODO: 这里可以跳转到结果页面或返回结果
                    Log.d(TAG, "抠图API调用成功 - Mock");
                });
                
            } catch (InterruptedException e) {
                runOnUiThread(() -> {
                    showLoading(false);
                    Toast.makeText(this, "处理失败，请重试", Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }
    
    private void clearMask() {
        maskDrawingView.clearMask();
        maskBitmap = null;
        btnUploadMask.setText("上传遮罩");
        btnDrawMask.setText("绘制遮罩");
        updateMaskButtons();
        Toast.makeText(this, "遮罩已清除", Toast.LENGTH_SHORT).show();
    }

    private void updateMaskButtons() {
        // 根据是否有遮罩来显示/隐藏编辑按钮
        boolean hasMask = maskBitmap != null || maskDrawingView.hasMask();
        btnEditMask.setVisibility(hasMask ? View.VISIBLE : View.GONE);
    }

    private void showLoading(boolean show) {
        progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        btnSubmit.setEnabled(!show);
        btnSubmit.setText(show ? "处理中..." : "提交处理");
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (resultCode == RESULT_OK && data != null) {
            Uri imageUri = data.getData();
            
            try {
                InputStream inputStream = getContentResolver().openInputStream(imageUri);
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                
                if (requestCode == REQUEST_ORIGINAL_IMAGE) {
                    originalBitmap = bitmap;
                    originalImageUriString = imageUri.toString(); // 保存原图URI
                    ivOriginalImage.setImageBitmap(bitmap);
                    ivOriginalImage.setVisibility(View.VISIBLE);

                    // 隐藏上传提示，显示遮罩绘制层
                    llUploadHint.setVisibility(View.GONE);
                    maskDrawingView.setVisibility(View.VISIBLE);

                    // 根据图片尺寸调整容器大小
                    adjustImageContainerSize(bitmap);

                    maskDrawingView.setOriginalBitmap(bitmap);
                    btnUploadOriginal.setText("重新上传原图");

                } else if (requestCode == REQUEST_MASK_IMAGE) {
                    maskBitmap = bitmap;

                    // 如果还没有原图，先根据遮罩图片调整容器大小
                    if (originalBitmap == null) {
                        adjustImageContainerSize(bitmap);
                        llUploadHint.setVisibility(View.GONE);
                        maskDrawingView.setVisibility(View.VISIBLE);
                    }

                    maskDrawingView.setMaskBitmap(bitmap);
                    btnUploadMask.setText("重新上传遮罩");
                    updateMaskButtons();
                }
            } catch (FileNotFoundException e) {
                Toast.makeText(this, "图片加载失败", Toast.LENGTH_SHORT).show();
                Log.e(TAG, "图片加载失败: " + e.getMessage());
            }
        }

        if (resultCode == MaskDrawingActivity.RESULT_MASK_CREATED && requestCode == REQUEST_DRAW_MASK) {
            // 处理绘制遮罩的结果
            if (data != null) {
                byte[] maskBytes = data.getByteArrayExtra(MaskDrawingActivity.EXTRA_MASK_BITMAP);
                if (maskBytes != null) {
                    maskBitmap = BitmapFactory.decodeByteArray(maskBytes, 0, maskBytes.length);
                    if (maskBitmap != null) {
                        maskDrawingView.setMaskBitmap(maskBitmap);
                        btnDrawMask.setText("重新绘制遮罩");
                        updateMaskButtons();
                        Toast.makeText(this, "遮罩绘制完成", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        
        if (requestCode == REQUEST_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "需要存储权限才能选择图片", Toast.LENGTH_LONG).show();
            }
        }
    }
    
    private void adjustImageContainerSize(Bitmap bitmap) {
        if (bitmap == null) return;

        float density = getResources().getDisplayMetrics().density;
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        int maxWidth = screenWidth - (int) (32 * density); // 减去左右padding
        int maxHeight = (int) (400 * density); // 最大高度400dp
        int minWidth = (int) (200 * density); // 最小宽度200dp
        int minHeight = (int) (150 * density); // 最小高度150dp

        int bitmapWidth = bitmap.getWidth();
        int bitmapHeight = bitmap.getHeight();

        // 计算缩放比例，保持宽高比
        float scaleX = (float) maxWidth / bitmapWidth;
        float scaleY = (float) maxHeight / bitmapHeight;
        float scale = Math.min(scaleX, scaleY);

        // 计算最终尺寸
        int finalWidth = Math.max(minWidth, (int) (bitmapWidth * scale));
        int finalHeight = Math.max(minHeight, (int) (bitmapHeight * scale));

        // 调整统一容器大小
        ViewGroup.LayoutParams containerParams = flImageContainer.getLayoutParams();
        containerParams.width = finalWidth;
        containerParams.height = finalHeight;
        flImageContainer.setLayoutParams(containerParams);

        Log.d(TAG, "调整容器尺寸: " + finalWidth + "x" + finalHeight +
                   " (原图: " + bitmapWidth + "x" + bitmapHeight +
                   ", 缩放: " + scale + ")");
    }

    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return true;
    }
}
